import React, { useState, useRef, forwardRef } from 'react';
import { Card, Form, Input, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import http from '../utils/http'
import Captcha from './captcha';
const PLogn = () => {
  const [form] = Form.useForm();
  const [countdown, setCountdown] = useState(0);
  const [captchaValid, setCaptchaValid] = useState(false);
  const timerRef = useRef(null);
  const captchaRef = useRef(null);
  const navigate = useNavigate();
  // 发送短信验证码
  const sendSmsCode = async (phone) => {
    try {
      await http.post('/sendCode', { phoneNumber: phone });
      message.success('验证码已发送');
      startCountdown();
    } catch (error) {
      message.error('发送失败: ' + error.message);
    }
  };

  // 启动60秒倒计时
  const startCountdown = () => {
    setCountdown(60);
    timerRef.current = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timerRef.current);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    if (!captchaValid) {
      message.error('请先完成图形验证');
      return;
    }

    try {
      const res = await http.post('/sms/verify', {
        phone: values.phone,
        code: values.code,
        captcha: values.captcha
      });
      localStorage.setItem('token', JSON.stringify(res.data.token))
      message.success('登录成功');
      // 后续跳转逻辑...
      navigate('/');
    } catch (error) {
      message.error('登录失败: ' + error.message);
    }
  };

  return (
    <Card title="手机验证码登录" style={{ width: 400, margin: '100px auto' }}>
      <Form form={form} onFinish={handleSubmit}>
        <Form.Item
          name="phone"
          rules={[
            { required: true, message: '请输入手机号' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
          ]}
        >
          <Input placeholder="请输入手机号" maxLength={11} />
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            // { required: true, message: '请输入图形验证码' },
            {
              validator: (_, value) =>
                captchaValid ? Promise.resolve() : Promise.reject(new Error('验证码错误'))
            }
          ]}
        >
          <Captcha
            ref={captchaRef}
            onCaptchaChange={(valid) => setCaptchaValid(valid)}
          />
        </Form.Item>
        <Form.Item
          name="code"
          rules={[
            { required: true, message: '请输入验证码' },
          ]}
        >
          <Input
            placeholder="请输入验证码"
            maxLength={6}
            addonAfter={
              <Button
                type="link"
                disabled={countdown > 0 || !captchaValid}
                onClick={() => {
                  const phone = form.getFieldValue('phone');
                  if (/^1[3-9]\d{9}$/.test(phone)) {
                    sendSmsCode(phone);
                  } else {
                    message.error('请先输入正确手机号');
                  }
                }}
              >
                {countdown > 0 ? `${countdown}秒后重发` : '获取验证码'}
              </Button>
            }
          />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
      </Form>
      <p style={{ position: 'fixed', bottom: 0, left: 85, fontSize: 14 }}>还没有账号？
        <span style={{ color: '#4096ff' }} onClick={() => { navigate('/enroll') }}>注册</span>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<span style={{ color: '#4096ff' }} onClick={() => { navigate('/login') }}>密码登录</span> |  <a onClick={() => {
          localStorage.removeItem('token');
          navigate('/')
        }}>点击游客登陆</a>
      </p>
    </Card>
  );
};

export default PLogn;